package com.hmkj.web.config;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.exception.BussinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class ExceptionHander {

    @ResponseBody
    @ExceptionHandler({Exception.class})
    public ResultEntity defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error(e.toString(), e);
        ResultEntity resultEntity = new ResultEntity();
        if (e instanceof BussinessException) {
            resultEntity.setMessage(e.getMessage());
            resultEntity.setCode(BussinessException.Code.E400.code);
            if (((BussinessException) e).getCode() != null) {
                resultEntity.setCode(((BussinessException) e).getCode().code);
                resultEntity.setMessage(((BussinessException) e).getCode().msg);
            }
            if (((BussinessException) e).getData() != null)
                resultEntity.setData(((BussinessException) e).getData());
        } else {
            e.printStackTrace();
            resultEntity.setCode(BussinessException.Code.E400.code);
            resultEntity.setMessage(BussinessException.Code.E400.msg);
        }
        return resultEntity;
    }
}
